import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import axios from 'axios';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell } from 'recharts';
import logger from '../../utils/logger';

const DashboardContainer = styled.div`
  /* 确保Dashboard在ContentWrapper内部完全居中显示 */
  width: 100%;
  margin: 0 auto;
  box-sizing: border-box;
`;

const PageTitle = styled.h2`
  margin-bottom: 24px;
  color: #1f2937;
  font-size: 24px;
  font-weight: 600;
`;

const StatsGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
`;

const StatCard = styled.div`
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s, box-shadow 0.2s;
  display: flex;
  align-items: center;
  position: relative;
  overflow: hidden;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }
  
  // 不同卡片不同颜色的装饰条
  &:nth-child(1)::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 4px;
    height: 100%;
    background: linear-gradient(to bottom, #3b82f6, #2563eb);
  }
  
  &:nth-child(2)::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 4px;
    height: 100%;
    background: linear-gradient(to bottom, #10b981, #059669);
  }
  
  &:nth-child(3)::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 4px;
    height: 100%;
    background: linear-gradient(to bottom, #f59e0b, #d97706);
  }
  
  &:nth-child(4)::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 4px;
    height: 100%;
    background: linear-gradient(to bottom, #6366f1, #4f46e5);
  }
`;

const StatIcon = styled.div`
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: ${props => props.color};
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  margin-right: 16px;
`;

const StatContent = styled.div`
  flex: 1;
`;

const StatTitle = styled.div`
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 4px;
`;

const StatValue = styled.div`
  font-size: 32px;
  font-weight: 700;
  color: #1f2937;
`;

const StatChange = styled.div`
  font-size: 12px;
  display: flex;
  align-items: center;
  
  ${({ positive }) => (
    positive 
      ? 'color: #10b981;' 
      : 'color: #ef4444;'
  )}
`;

const ChartsSection = styled.div`
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  margin-bottom: 32px;
  
  @media (max-width: 1024px) {
    grid-template-columns: 1fr;
  }
`;

const ChartCard = styled.div`
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
`;

const ChartTitle = styled.h3`
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 16px;
`;

const ChartPlaceholder = styled.div`
  height: 240px;
  background-color: #f3f4f6;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #9ca3af;
  font-size: 14px;
`;

const RecentActivities = styled.div`
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
`;

const SectionTitle = styled.h3`
  font-size: 18px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 16px;
`;

const ActivityList = styled.ul`
  list-style: none;
  padding: 0;
  margin: 0;
`;

const ActivityItem = styled.li`
  display: flex;
  padding: 12px 0;
  border-bottom: 1px solid #f3f4f6;
  
  &:last-child {
    border-bottom: none;
  }
`;

const ActivityIcon = styled.div`
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: ${props => props.color};
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
  margin-right: 12px;
`;

const ActivityContent = styled.div`
  flex: 1;
`;

const ActivityText = styled.div`
  font-size: 14px;
  color: #374151;
  margin-bottom: 4px;
`;

const ActivityTime = styled.div`
  font-size: 12px;
  color: #9ca3af;
`;

const Dashboard = () => {
  const [stats, setStats] = useState({
    totalUsers: 0,
    activeUsers: 0,
    vipUsers: 0,
    totalAnalyses: 0,
    userGrowthRate: 0,
    vipConversionRate: 0,
    dailyActiveUsers: 0,
    dailyRevenue: 0,
    monthlyRevenue: 0,
    totalRevenue: 0,
    averageOrderValue: 0
  });
  
  useEffect(() => {
    // 记录进入仪表盘页面
    logger.info('进入后台管理仪表盘页面');
  }, []);
  const [loading, setLoading] = useState(true);
  const [recentActivities, setRecentActivities] = useState([]);
  const [growthData, setGrowthData] = useState([]);
  const [analysisTypeData, setAnalysisTypeData] = useState([]);
  const [revenueData, setRevenueData] = useState([]);

  // 模拟数据加载
  useEffect(() => {
    const fetchDashboardData = async () => {
      try {
        // 在实际项目中，这里应该调用真实的API接口
        // const response = await axios.get('/admin/stats/dashboard');
        // setStats(response.data);
        
        // 模拟数据加载延迟
        setTimeout(() => {
          setStats({
            totalUsers: 15263,
            activeUsers: 9872,
            vipUsers: 1245,
            totalAnalyses: 45621,
            userGrowthRate: 12.5,
            vipConversionRate: 9.8,
            dailyActiveUsers: 2453,
            dailyRevenue: 5268.50,
            monthlyRevenue: 125432.75,
            totalRevenue: 1254326.80,
            averageOrderValue: 128.50
          });
          
          // 模拟最近活动数据
          setRecentActivities([
            {
              id: 1,
              type: 'purchase',
              user: 'vip456',
              message: '购买了VIP会员',
              time: '17分钟前',
              color: '#3b82f6'
            },
            {
              id: 2,
              type: 'register',
              user: 'lucky888',
              message: '新用户注册成功',
              time: '30分钟前',
              color: '#10b981'
            },
            {
              id: 3,
              type: 'analysis',
              user: 'user789',
              message: '完成了面相分析',
              time: '1小时前',
              color: '#8b5cf6'
            },
            {
              id: 4,
              type: 'system',
              user: 'system',
              message: '系统更新成功 - 版本 v1.2.0',
              time: '3小时前',
              color: '#6366f1'
            },
            {
              id: 5,
              type: 'content',
              user: 'admin',
              message: '新增10条面相分析模板',
              time: '昨天',
              color: '#f59e0b'
            }
          ]);
          
          // 模拟用户增长趋势数据
          setGrowthData([
            { month: '1月', users: 8500 },
            { month: '2月', users: 9200 },
            { month: '3月', users: 10100 },
            { month: '4月', users: 11500 },
            { month: '5月', users: 13200 },
            { month: '6月', users: 15263 }
          ]);
          
          // 模拟分析类型分布数据
          setAnalysisTypeData([
            { name: '面相分析', count: 21567 },
            { name: '手相分析', count: 12456 },
            { name: '八字分析', count: 11598 }
          ]);
          
          // 模拟收入趋势数据
          setRevenueData([
            { month: '1月', revenue: 85000 },
            { month: '2月', revenue: 92000 },
            { month: '3月', revenue: 101000 },
            { month: '4月', revenue: 115000 },
            { month: '5月', revenue: 132000 },
            { month: '6月', revenue: 152000 }
          ]);
          
          setLoading(false);
        }, 800);
      } catch (error) {
        console.error('获取仪表板数据失败:', error);
        setLoading(false);
      }
    };

    fetchDashboardData();
  }, []);

  const getActivityIcon = (type) => {
    switch(type) {
      case 'login':
        return '👤';
      case 'purchase':
        return '💰';
      case 'register':
        return '👋';
      case 'analysis':
        return '🔍';
      case 'feedback':
        return '💬';
      case 'system':
        return '🔄';
      case 'content':
        return '📝';
      default:
        return '📋';
    }
  };

  return (
    <DashboardContainer>
      <PageTitle>数据监控大屏</PageTitle>
      
      <StatsGrid>
        <StatCard>
          <StatIcon color="#3b82f6">👥</StatIcon>
          <StatContent>
            <StatTitle>总用户数</StatTitle>
            <StatValue>{loading ? '加载中...' : stats.totalUsers.toLocaleString()}</StatValue>
            <StatChange positive={stats.userGrowthRate > 0}>
              {stats.userGrowthRate > 0 ? '↑' : '↓'} {Math.abs(stats.userGrowthRate)}% 较上月
            </StatChange>
          </StatContent>
        </StatCard>
        
        <StatCard>
          <StatIcon color="#10b981">📱</StatIcon>
          <StatContent>
            <StatTitle>活跃用户</StatTitle>
            <StatValue>{loading ? '加载中...' : stats.activeUsers.toLocaleString()}</StatValue>
            <StatChange positive={true}>
              ↑ 8.3% 较上月
            </StatChange>
          </StatContent>
        </StatCard>
        
        <StatCard>
          <StatIcon color="#f59e0b">⭐</StatIcon>
          <StatContent>
            <StatTitle>VIP用户</StatTitle>
            <StatValue>{loading ? '加载中...' : stats.vipUsers.toLocaleString()}</StatValue>
            <StatChange positive={stats.vipConversionRate > 0}>
              {stats.vipConversionRate > 0 ? '↑' : '↓'} {Math.abs(stats.vipConversionRate)}% 较上月
            </StatChange>
          </StatContent>
        </StatCard>
        
        <StatCard>
          <StatIcon color="#6366f1">🔍</StatIcon>
          <StatContent>
            <StatTitle>分析总次数</StatTitle>
            <StatValue>{loading ? '加载中...' : stats.totalAnalyses.toLocaleString()}</StatValue>
            <StatChange positive={true}>
              ↑ 15.2% 较上月
            </StatChange>
          </StatContent>
        </StatCard>
      </StatsGrid>

      {/* 财务数据统计卡片 */}
      <StatsGrid>
        <StatCard>
          <StatIcon color="#ec4899">💰</StatIcon>
          <StatContent>
            <StatTitle>今日收入</StatTitle>
            <StatValue>
              {loading ? '加载中...' : `¥${stats.dailyRevenue.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`}
            </StatValue>
            <StatChange positive={true}>
              ↑ 15.3% 较昨日
            </StatChange>
          </StatContent>
        </StatCard>
        
        <StatCard>
          <StatIcon color="#8b5cf6">📊</StatIcon>
          <StatContent>
            <StatTitle>本月收入</StatTitle>
            <StatValue>
              {loading ? '加载中...' : `¥${stats.monthlyRevenue.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`}
            </StatValue>
            <StatChange positive={true}>
              ↑ 12.8% 较上月
            </StatChange>
          </StatContent>
        </StatCard>
        
        <StatCard>
          <StatIcon color="#14b8a6">💼</StatIcon>
          <StatContent>
            <StatTitle>总收入</StatTitle>
            <StatValue>
              {loading ? '加载中...' : `¥${stats.totalRevenue.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`}
            </StatValue>
            <StatChange positive={true}>
              ↑ 25.6% 较去年同期
            </StatChange>
          </StatContent>
        </StatCard>
        
        <StatCard>
          <StatIcon color="#6366f1">🎯</StatIcon>
          <StatContent>
            <StatTitle>平均订单金额</StatTitle>
            <StatValue>
              {loading ? '加载中...' : `¥${stats.averageOrderValue.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`}
            </StatValue>
            <StatChange positive={true}>
              ↑ 5.2% 较上月
            </StatChange>
          </StatContent>
        </StatCard>
      </StatsGrid>

      <ChartsSection>
        <ChartCard>
          <ChartTitle>用户增长趋势</ChartTitle>
          {loading ? (
            <ChartPlaceholder>
              <div>加载中...</div>
            </ChartPlaceholder>
          ) : (
            <ResponsiveContainer width="100%" height={300}>
              <LineChart
                data={growthData}
                margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
              >
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="month" />
                <YAxis />
                <Tooltip formatter={(value) => value.toLocaleString()} />
                <Legend />
                <Line type="monotone" dataKey="users" stroke="#3b82f6" strokeWidth={2} dot={{ r: 4 }} activeDot={{ r: 6 }} />
              </LineChart>
            </ResponsiveContainer>
          )}
        </ChartCard>
        
        <ChartCard>
          <ChartTitle>收入趋势</ChartTitle>
          {loading ? (
            <ChartPlaceholder>
              <div>加载中...</div>
            </ChartPlaceholder>
          ) : (
            <ResponsiveContainer width="100%" height={300}>
              <BarChart
                data={revenueData}
                margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
              >
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="month" />
                <YAxis />
                <Tooltip formatter={(value) => `¥${value.toLocaleString()}`} />
                <Legend />
                <Bar dataKey="revenue" fill="#8b5cf6" name="月收入" />
              </BarChart>
            </ResponsiveContainer>
          )}
        </ChartCard>
        
        <ChartCard>
          <ChartTitle>分析类型分布</ChartTitle>
          {loading ? (
            <ChartPlaceholder>
              <div>加载中...</div>
            </ChartPlaceholder>
          ) : (
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={analysisTypeData}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                  outerRadius={100}
                  fill="#8884d8"
                  dataKey="count"
                >
                  {analysisTypeData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={['#3b82f6', '#10b981', '#f59e0b'][index % 3]} />
                  ))}
                </Pie>
                <Tooltip formatter={(value) => value.toLocaleString()} />
              </PieChart>
            </ResponsiveContainer>
          )}
        </ChartCard>
        
        <ChartCard>
          <ChartTitle>今日分析统计</ChartTitle>
          {loading ? (
            <ChartPlaceholder>
              <div>加载中...</div>
            </ChartPlaceholder>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
              <div style={{ fontSize: '3rem', fontWeight: 'bold', color: '#6366f1', marginBottom: '1rem' }}>
                {Math.round(stats.totalAnalyses / 30).toLocaleString()}
              </div>
              <div style={{ fontSize: '1.1rem', color: '#4a5568' }}>今日完成分析次数</div>
              <div style={{ marginTop: '1rem', display: 'flex', gap: '2rem', textAlign: 'center' }}>
                <div>
                  <div style={{ fontSize: '1.5rem', fontWeight: 'bold', color: '#3b82f6' }}>47%</div>
                  <div style={{ fontSize: '0.9rem', color: '#718096' }}>面相分析</div>
                </div>
                <div>
                  <div style={{ fontSize: '1.5rem', fontWeight: 'bold', color: '#10b981' }}>27%</div>
                  <div style={{ fontSize: '0.9rem', color: '#718096' }}>手相分析</div>
                </div>
                <div>
                  <div style={{ fontSize: '1.5rem', fontWeight: 'bold', color: '#f59e0b' }}>26%</div>
                  <div style={{ fontSize: '0.9rem', color: '#718096' }}>八字分析</div>
                </div>
              </div>
            </div>
          )}
        </ChartCard>
      </ChartsSection>

      <RecentActivities>
        <SectionTitle>最近活动</SectionTitle>
        <ActivityList>
          {recentActivities.map(activity => (
            <ActivityItem key={activity.id}>
              <ActivityIcon color={activity.color}>
                {getActivityIcon(activity.type)}
              </ActivityIcon>
              <ActivityContent>
                <ActivityText>
                  <strong>{activity.user}</strong> {activity.message}
                </ActivityText>
                <ActivityTime>{activity.time}</ActivityTime>
              </ActivityContent>
            </ActivityItem>
          ))}
        </ActivityList>
      </RecentActivities>
    </DashboardContainer>
  );
};

export default Dashboard;